# -*- coding: utf-8 -*-
# @File     : login_register.py
# @Author   : bingjia
# @Time     : 2020/6/4
# @Desc     : 注册登录form表单校验

from django.shortcuts import redirect
from django import forms as django_forms
from django.forms import fields as django_fields


def check_login(func):
    """
    登录验证装饰器
    :param func: 待验证操作
    :return:
    """

    def inner(request, *args, **kwargs):
        if request.session.get("user_info"):
            return func(request, *args, **kwargs)
        else:
            return redirect("/users/login/")

    return inner


class BaseForm(object):
    """
    Form基类
    """

    def __init__(self, request, *args, **kwargs):
        self.request = request
        super(BaseForm, self).__init__(*args, **kwargs)


class LoginForm(BaseForm, django_forms.Form):
    """
    验证登录的Form
    """
    username = django_fields.CharField(
        max_length=32,
        error_messages={"required": "用户名不能为空!",
                        "max_length": "用户名长度不能大于32个字符!"}
    )
    password = django_fields.CharField(
        min_length=6,
        max_length=32,
        error_messages={"required": "密码不能为空!",
                        "min_length": "密码长度不能小于6个字符!",
                        "max_length": "密码长度不能大于32个字符!"}
    )


class RegisterForm(BaseForm, django_forms.Form):
    """
    验证注册的Form
    """
    username = django_fields.CharField(
        max_length=32,
        error_messages={"required": "用户名不能为空!",
                        "max_length": "用户名长度不能大于32个字符!"}
    )
    fullname = django_fields.CharField(
        max_length=32,
        error_messages={"required": "全名不能为空!",
                        "max_length": "全名长度不能大于32个字符!"}
    )
    phone = django_fields.CharField(
        min_length=11,
        max_length=11,
        error_messages={"required": "手机号不能为空!",
                        "max_length": "手机号长度11个字符!"}
    )
    password = django_fields.CharField(
        min_length=6,
        max_length=32,
        error_messages={"required": "密码不能为空!",
                        "min_length": "密码长度不能小于6个字符!",
                        "max_length": "密码长度不能大于32个字符!"}
    )
